package cn.tedu.serializable;
/**
 * @Author 金帮嘉诚
 * @Date 2021-06-19 周六 11:27
 */
/*本类用于测试*/

import java.io.*;

/**
 知识点：
 序列化与反序列化，UID要一致
 UID默认自动生成一个，改变类中属性或方法，UID会更改
 所以可以自己定义一个UID（long类型），只要这个值不修改，不论编译次数，UID都不会更改
 */
public class TestSerializable {
    public static void main(String[] args) {
        method1();
        method2();
    }

    private static void method2() {
        ObjectInputStream in =null;

        try {
            in=new ObjectInputStream(new BufferedInputStream(new FileInputStream("d:\\ready\\1.txt")));

            Object obj=in.readObject();
            System.out.println("obj = " + obj);

            System.out.println("恭喜！反序列化成功！");

        } catch (Exception e) {
            System.out.println("抱歉！反序列化失败！");
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void method1() {
        ObjectOutputStream out=null;

        try {
            out=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("d:\\ready\\1.txt")));

            Student s=new Student("人类",10,"地球",'男');
            out.writeObject(s);
            out.flush();
            System.out.println("恭喜！序列化成功！");
        } catch (IOException e) {
            System.out.println("抱歉！序列化失败！");
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
